<template>
	<!-- 保养作业时长 -->
	<cardTemplate :loading="loading" :opt="cardSetting" title="工单保养作业时长" @filterFun="getFilterFun" :setTime="filter"
		name="workTime" :safeAreaBottom="safeAreaBottom">
		<totals v-if="filter.type == 1" :list="totalList"></totals>
		<view class="title-d" v-if="filter.type == 1 && userList.length && userList.length > 1">工单保养作业时长明细</view>
		<view class="data-type-line" v-if="filter.type == 2 && userList.length && userList.length > 1"></view>
		<view class="data-types" v-if="userList.length">
			<sTabs v-if="filter.type == 1 && memberList.length > 1 && userList.length > 1"
				@change="changeTab('timeOpt', $event)" :list="timeOpt.typeList" :idx="timeOpt.typeIdx"></sTabs>
			<sTabs v-if="filter.type == 2 && userList.length > 1" @change="changeLineType('timeOpt', $event)"
				:list="timeOpt.groupList" :idx="timeOpt.lineType" class="data-type-tabs"></sTabs>

			<view class="data-types-right" v-if="filter.type == 2">
				<view class="mbs-type" v-if="timeOpt.lineType && userList.length > 1" @click="changeMbs('timeOpt')">
					<image src="@/static/images/chart.png" mode=""></image>
					对比名单
				</view>
				<view class="date-type" @click="showSPicker('timeOpt')">
					{{ dateTypes[timeOpt.dateType] }}
					<image src="@/static/images/down.png" mode=""></image>
				</view>
			</view>
		</view>
		<!-- 折线图趋势对比类型 -->
		<view class="tag-block" v-if="filter.type == 2 && userList.length > 1 && timeOpt.lineType">
			<view @click="changeLineTag(index)" :class="['tag-block-item', timeOpt.tagIdx === index ? 'act' : '']"
				v-for="(item, index) in timeOpt.tags" :key="item.key">
				{{ item.name }}
			</view>
		</view>
		<!-- 折线图趋势对比类型 end -->
		<!-- 按组表格 -->
		<s-table :dataList="timeOpt.groupRecords" :totals="timeOpt.totals" :title="title"
			@toContractDetail="toContractDetail($event, timeOpt.typeIdx)" :headers="timeOpt.leaderHead"
			v-if="filter.type == 1 && userList.length && userList.length > 1 && timeOpt.typeIdx == 0"></s-table>
		<!-- 按人 -->
		<s-table :dataList="timeOpt.groupRecords" :headers="timeOpt.userHead"
			@toContractDetail="toContractDetail($event, timeOpt.typeIdx)" :totals="timeOpt.totals" :title="title"
			v-if="filter.type == 1 && userList.length && userList.length > 1 && timeOpt.typeIdx == 1"></s-table>
		<!-- 折线图趋势对比类型 end -->
		<view class="line-chart" v-if="filter.type == 2">
			<defaultBlock v-if="!timeOpt.hasData"></defaultBlock>

			<l-echart class="line" ref="timeOpt"></l-echart>
		</view>
	</cardTemplate>
</template>

<script>
import * as echarts from '@/subpages/components/lime-echart/static/echarts.min';
import LEchart from '@/subpages/components/lime-echart/components/l-echart/l-echart.vue';
import cardTemplate from '../components/card-template/card-template.vue';
import totals from '../components/card-template/totals.vue';
import { onelineOpt, moreLineOpt } from './chartSet.js';
import { getLastDates } from '@/utils/tools.js';
import defaultBlock from '../components/default.vue';
import { formatTime } from '@/utils/utils.js';
import sTable from '../../components/s-table/s-table.vue';
import sTabs from '../components/tabs.vue';
import {
	getWorkDurationNums,
	getWorkDurationPerson,
	getStatisticsDurationGroupRecords,
	getWorkDurationUserRecords,
	getWorkDurationLines,
	getWorkDurationGroupLines,
	getWorkDurationUserLines
} from '@/apis/statistic.js';
export default {
	name: 'workTime',
	components: { LEchart, cardTemplate, totals, defaultBlock, sTable, sTabs },
	props: {
		title: {
			type: [String],
			default: ''
		},
		groupId: [String, String],
		pageScrollTop: {
			type: [Number, String],
			default: 0
		},
		memberList: {
			type: Array,
			default: () => []
		},
		userList: {
			type: Array,
			default: () => []
		},
		safeAreaBottom: {
			type: [Number, String],
			default: 0
		}
	},
	data() {
		return {
			// 加载中
			loading: false,
			cardSetting: {
				titleTips: {
					show: false,
					content: ''
				}
			},
			dateTypes: ['按日', '按周', '按月'],
			totalList: [
				{
					val: 0,
					name: '已保养作业工单数'
				},
				{
					val: 0,
					name: '工单平均作业时长(分钟)'
				}
			],
			filter: {
				// 统计类型 1数量，2趋势
				type: 1, 
				// 日期范围 1今天，2近七天，3近30天，4自定义日期
				dateType: 2,
				startTime: '',
				endTime: '',
				useType: 0
			},
			timeOpt: {
				typeList: ['按组', '按人'],
				groupList: ['整体趋势', '趋势对比'],
				totals: {},
				// 保养作业时长配置
				hasData: false,
				// 0按组 1按人
				typeIdx: 0, 
				dateType: 0,
				lineOpts: {},
				// 1按组统计，2按人统计
				type: 1,
				// 0整体趋势 1趋势对比
				lineType: 0, 
				tagIdx: 0,
				// 选中的组
				lineTypeGroup: [], 
				// 选中的人
				lineTypeMbs: [], 
				// 累积作业时长(小时)
				val1: 0, 
				// 工单平均作业时长(分钟)
				val2: 0,
				leaderHead: [
					{   
						// 表头名称
						name: '组名',
						// 是否开启该列的排序功能
						sort: false, 
						checked: true,
						// 列宽
						width: 180,
						// 显示哪个字段
						key: 'name', 
						// 单位
						unit: '' 
					},
					{
						name: '已保养作业工单数',
						sort: true,
						checked: true,
						width: 210,
						key: 'planTotal',

					},
					{
						name: '工单平均作业时长/(分钟)',
						sort: true,
						checked: true,
						width: 270,
						key: 'workTimeMinAve',
						unit: '',

					}
				],
				userHead: [
					{ 
						// 表头名称
						name: '组名', 
						// 是否开启该列的排序功能
						sort: false, 
						checked: true,
						// 列宽
						width: 180, 
						// 显示哪个字段
						key: 'name', 
						// 单位
						unit: '' 
					},
					{
						name: '已保养作业工单数',
						sort: true,
						checked: true,
						width: 200,
						key: 'planTotal'
					},
					{
						name: '工单平均作业时长/(分钟)',
						sort: true,
						checked: true,
						width: 260,
						key: 'workTimeMinAve',
						unit: ''
					},
				], 
				tags: [{ name: '已保养作业工单数', unit: '单', key: 'planTotal' }, { name: '工单平均作业时长', key: 'workTimeMinAve', unit: '分钟' }],
				linedata: {
					categories: [],
					series: []
				},
				chartData: {
					series: [{ name: '正常', data: 12, eleTotal: 76 }, { name: '异常', data: 15, eleTotal: 76 }]
				},
				// 组明细
				groupRecords: [], 
				// 人明细
				userRecords: [] 
			}
		};
	},
	created() {
		// 近七天
		// 默认近七天
		const dates = getLastDates(7); 
		this.filter.startTime = dates.startTime;
		this.filter.endTime = dates.endTime;
	},
	computed: {
		isToday() {
			let today = formatTime(new Date().getTime());
			let flag = false;
			if (this.filter.startTime == today && this.filter.startTime == today) {
				flag = true;
			}
			return flag;
		},
	},
	methods: {
		// showSPicker() {
		// 	this.$emit('showSPicker', this.timeOpt);
		// },
		// 修改某个图表日月周
		changeDateType(res) {
			console.log('修改某个图表日月周', res);
			this['timeOpt'].dateType = res.value;
			this.getUserTrend();
		},
		showSPicker() {
			// eslint-disable-next-line vue/custom-event-name-casing
			this.$emit('showSPicker', this.timeOpt);
		},
		// 自定义按组按人趋势对比
		changeMbsFuc(res) {
			console.log('自定义按组按人趋势对比', res);
			this['timeOpt'].type = res.type;
			if (res.type == 1) {
				this['timeOpt'].lineTypeGroup = JSON.parse(JSON.stringify(res.acts));
			}
			if (res.type == 2) {
				this['timeOpt'].lineTypeMbs = JSON.parse(JSON.stringify(res.acts));
			}
			this.getUserTrend();
		},

		// 打开对比名等
		changeMbs() {
			// eslint-disable-next-line vue/custom-event-name-casing
			this.$emit('changeMbs', this.timeOpt);
		},
		// 截取日期前几位
		changeDateVal(list) {
			if (!list || list.length == 0) {
				return [];
			}
			let relist = [];
			for (let i = 0; i < list.length; i++) {
				let date = list[i];
				if (date.indexOf('月') != -1) {
					relist.push(date);
				} else {
					if (date.indexOf('~') != -1) {
						// 按周
						let arr = date.split('~');
						try {
							relist.push(arr[0].slice(5) + '~' + arr[1].slice(5));
						} catch (e) {
							// TODO handle the exception
							relist.push('');
						}
					} else {
						relist.push(date.slice(5));
					}
				}
			}
			return relist;
		},

		// 表格点击事件
		toContractDetail(res, typdIdx) {
			const { item, key } = res;
			console.log(item, key, typdIdx);
			if (key == 'name' && this.memberList.length) {
				if (!this.memberList.length) {
					return;
				}
				// 数据下转
				let list = [];
				let groupId = '';
				if (this.memberList.length == 1) {
					list = this.memberList[0].children;
					groupId = this.memberList[0].id;
				} else {
					list = this.memberList;
				}
				if (typdIdx == 1 && this.memberList.length > 1) {
					// 按人对比 查询子集维保员
					for (let i = 0; i < list.length; i++) {
						for (let j = 0; j < list[i].children.length; j++) {
							if (list[i].children[j].name == item.name) {
								const storage = {
									groupId: this.groupId,
									id: list[i].children[j].id,
									title: item.name
								};
								this.toDeepPage(storage);
								return;
							}
						}
					}
				} else {
					console.log(item, key, list);
					for (let i = 0; i < list.length; i++) {
						if (list[i].name == item.name) {
							if (list[i].type == 2) {
								// 人单位
								const storage = {
									groupId: groupId,
									id: list[i].id,
									title: item.name
								};
								this.toDeepPage(storage);
							} else {
								// 组单位
								groupId = list[i].id;
								let ids = [];
								list[i].children.forEach(item => {
									ids.push(item.id);
								});
								const storage = {
									groupId: groupId,
									id: ids.join(','),
									groupList: [list[i]],
									title: item.name
								};
								this.toDeepPage(storage);
							}
							return;
						}
					}
				}
			}
		},
		// 数据下转
		toDeepPage(data) {
			console.log('数据下转', data);
			data.filter = this.filter;
			data.tabNums = this.tabNums;
			uni.setStorage({
				key: 'statistical' + (Number(this.childDeep || 0) + 1),
				data: data,
				success: () => {
					uni.navigateTo({
						url: `./statistical?tabIdx=2&childDeep=${Number(this.childDeep || 0) + 1}`
					});
				},
				fail: err => {
					console.log(err);
				}
			});
		},

		// 修改筛选条件
		getFilterFun(res) {
			console.log('修改筛选条件', res);
			if (res.applyToAll) {
				// eslint-disable-next-line vue/custom-event-name-casing
				this.$emit('applyToAll', res);
			}
			this.filter = res;
			this.initData();
		},
		initData(data) {
			console.log('worktime', data);
			if (this.userList.length == 0) {
				return;
			}
			this.loading = true;
			console.log(this.userList, this.timeOpt.typeIdx);
			if (data) {
				if (data.applyToAll) {
					this.filter.dateType = data.dateType;
					this.filter.startTime = data.startTime;
					this.filter.endTime = data.endTime;
				} else {
					this.filter = data;
				}
			}
			if (this.memberList.length <= 1) {
				this.timeOpt.typeIdx = 1;
			}
			if (this.filter.type == 1) {
				this.getTotals();
				if (this.userList.length > 1) {
					// 个人
					this.getGroupStatistic(this.tabNums); 
				} else {
					// 多人
					this.getUserStatistic(this.tabNums); 
				}
			} else {
				this.timeOpt.dateType = 0;
				this.timeOpt.lineType = 0;
				this.timeOpt.lineTypeGroup = [];
				this.timeOpt.lineTypeMbs = [];

				this.getUserTrend();
			}
		},
		changeTab(key, idx) {
			this['timeOpt'].typeIdx = idx;
			if (this.userList.length > 1) {
				// 个人
				this.getGroupStatistic(this.tabNums); 
			} else {
				// 多人
				this.getUserStatistic(this.tabNums);
			}
		},
		// 获取统计数量
		getTotals() {
			// let arr = this.getGroupList();
			getWorkDurationNums({
				startDate: this.filter.startTime,
				endDate: this.filter.endTime,
				// deptGroups: arr,
				userIds: this.userList,
				useType: this.filter.useType == 2 ? '' : this.filter.useType
			}).then(res => {
				this.totalList[0].val = res.data.planTotal;
				this.totalList[1].val = res.data.workTimeMinAve;
			});
		},

		// 单人保养统计 types：年审类型 inits：初始加载全部 corr：加载对应数据
		// eslint-disable-next-line no-unused-vars
		getUserStatistic(types, inits = 1, corr = 1) {
			let objs = {
				startDate: this.filter.startTime,
				endDate: this.filter.endTime,
				userIds: this.userList,
				useType: this.filter.useType == 2 ? '' : this.filter.useType,
				dataType: Number(this.timeOpt.dateType) + 1
			};

			getWorkDurationPerson(objs)
				.then(res => {
					this.totalList[0].val = res.data.planTotal;
					this.totalList[1].val = res.data.workTimeMinAve;
					this.loading = false;
				})
				.catch(() => {
					this.loading = false;
				});
		},
		// 获取组组织架构列表
		getGroupList() {
			let arr = [
				{
					deptId: -1,
					deptName: '全部',
					userIds: this.userList,
					startDate: this.filter.startTime,
					endDate: this.filter.endTime
				}
			];
			for (var i = 0; i < this.memberList.length; i++) {
				const item = {
					deptId: this.memberList[i].id,
					deptName: this.memberList[i].name,
					userIds: []
				};
				for (var j = 0; j < this.memberList[i].children.length; j++) {
					item.userIds.push(this.memberList[i].children[j].id);
				}
				arr.push(item);
			}
			return arr;
		},

		// 按组统计 types：年审类型 inits：初始加载全部 corr：加载对应数据
		// eslint-disable-next-line no-unused-vars
		getGroupStatistic(type, inits = 1, corr = 1) {
			if (type === 0 || type === 1) {
				// 年审类型
				// eslint-disable-next-line no-undef
				obj.useType = type;
			}

			if (this.timeOpt.typeIdx == 0) {
				let arr = this.getGroupList();
				getStatisticsDurationGroupRecords({
					startDate: this.filter.startTime,
					endDate: this.filter.endTime,
					deptGroups: arr,
					useType: this.filter.useType == 2 ? '' : this.filter.useType
				})
					.then(res => {
						const list = res.data;
						for (var i = 0; i < list.length; i++) {
							list[i].name = list[i].label;
							list[i].allTime = Number(list[i].byWorkTimeTotal || 0) + Number(list[i].wxWorkTimeTotal || 0) + Number(list[i].pjWorkTimeTotal || 0);
						}
						this.setGeoupData(list, 'timeOpt');
						this.loading = false;
					})
					.catch(() => {
						this.loading = false;
					});
			} else {
				getWorkDurationUserRecords({
					startDate: this.filter.startTime,
					endDate: this.filter.endTime,
					userIds: this.userList,
					useType: this.filter.useType == 2 ? '' : this.filter.useType
				})
					.then(res => {
						const list = res.data;
						for (var i = 0; i < list.length; i++) {
							list[i].name = list[i].label;
							list[i].allTime = Number(list[i].byWorkTimeTotal || 0) + Number(list[i].wxWorkTimeTotal || 0) + Number(list[i].pjWorkTimeTotal || 0);
						}
						this.setGeoupData(list, 'timeOpt');
						this.loading = false;
					})
					.catch(() => {
						this.loading = false;
					});
			}
		},
		// 提取表格全部数据
		setGeoupData(arr, key) {
			let list = [];
			for (let i = 0; i < arr.length; i++) {
				if (arr[i].name == '全部') {
					this[key].totals = arr[i];
				} else {
					list.push(arr[i]);
				}
			}
			this[key].groupRecords = list;
		},

		setDefGroup(key) {
			if (this[key].type == 1) {
				// 按组对比，设置默认组数据
				if (this[key].lineTypeGroup.length) {
					// 检查是否有已选数据
				} else {
					let groups = [];
					for (let i = 0; i < this.memberList.length; i++) {
						groups.push(this.memberList[i].id);
					}
					if (groups.length > 5) {
						groups = groups.slice(0, 5);
					}
					this[key].lineTypeGroup = groups;
				}
			} else {
				// 按人对比，设置人默认数据
				if (this[key].lineTypeMbs.length) {
					// 检查是否有已选数据
				} else {
					let mbs = JSON.parse(JSON.stringify(this.userList));
					if (mbs.length > 5) {
						mbs = mbs.slice(0, 5);
					}
					this[key].lineTypeMbs = mbs;
				}
			}
			console.log(this.timeOpt);
		},

		// 切换某个图表的整体趋势或趋势对比
		changeLineType(key, idx) {
			console.log('切换图表的整体趋势或趋势对比', key, idx);
			this[key].lineType = idx;
			if (idx == 0) {
				// 整体趋势
				this.getWorkTimeLines();
				// this.getUserTrend(key, this[key], nums,1,1);
			}
			if (idx == 1) {
				// 趋势对比
				console.log('这里是趋势对比');
				if (this.memberList.length == 1) {
					// 如果没有下级组
					// 只能按人对比
					this[key].type = 2; 
				}
				this.setDefGroup(key);
				this.getUserTrend();
			}
		},

		// 趋势统计 types：年审类型 inits：初始加载全部 corr：加载对应数据
		getUserTrend() {
			if (this.memberList.length) {
				// 组长或经理
				if (this.timeOpt.lineType == 0) {
					// 整体
					this.getWorkTimeLines();
				} else {
					// 趋势对比
					if (this.timeOpt.type == 1) {
						// 按组
						this.getWorkTimeGroupLines();
					} else {
						// 按人
						this.getWorkTimeUserLines();
					}
				}
			} else {
				// 个人
				this.getWorkTimeLines();
			}
		},
		// 切换趋势对比模式下的折线图类型
		changeLineTag(index) {
			console.log('切换趋势对比模式下的折线图类型', index);
			this.timeOpt.tagIdx = index;
			this.getUserTrend();
		},

		// 整体趋势
		getWorkTimeLines() {
			getWorkDurationLines({
				startDate: this.filter.startTime,
				endDate: this.filter.endTime,
				userIds: this.userList,
				useType: this.filter.useType == 2 ? '' : this.filter.useType,
				dataType: Number(this.timeOpt.dateType) + 1
			}).then(res => {
				console.log('保养-作业时长-趋势整体', res);
				this.setLineData(res.data);
				this.loading = false;
			});
		},

		// 趋势对比-按组
		getWorkTimeGroupLines() {
			let arr = [];
			for (var i = 0; i < this.memberList.length; i++) {
				const item = {
					deptId: this.memberList[i].id,
					deptName: this.memberList[i].name,
					userIds: []
				};
				for (var j = 0; j < this.memberList[i].children.length; j++) {
					item.userIds.push(this.memberList[i].children[j].id);
				}
				if (this['timeOpt'].lineTypeGroup.indexOf(item.deptId) != -1) {
					arr.push(item);
				}
			}
			getWorkDurationGroupLines({
				startDate: this.filter.startTime,
				endDate: this.filter.endTime,
				deptGroups: arr,
				useType: this.filter.useType == 2 ? '' : this.filter.useType,
				dataType: Number(this.timeOpt.dateType) + 1,
				temp: this.timeOpt.tagIdx + 1
			}).then(res => {
				console.log('保养-作业时长-趋势对比-按组', res);
				this.setLineData(res.data, this.timeOpt.tagIdx == 0 ? '小时' : '分钟');
				this.loading = false;
			});
		},

		// 趋势对比-按人
		getWorkTimeUserLines() {
			console.log(this.timeOpt.lineTypeMbs);
			getWorkDurationUserLines({
				startDate: this.filter.startTime,
				endDate: this.filter.endTime,
				userIds: this.timeOpt.lineTypeMbs,
				useType: this.filter.useType == 2 ? '' : this.filter.useType,
				dataType: Number(this.timeOpt.dateType) + 1,
				temp: this.timeOpt.tagIdx + 1
			}).then(res => {
				console.log('保养-作业时长-趋势对比-按人', res);
				this.setLineData(res.data, this.timeOpt.tagIdx == 0 ? '小时' : '分钟');
				this.loading = false;
			});
		},

		// 重组趋势数据结构
		setLineData(list, unit) {
			const key = 'timeOpt';
			const linedata = {
				categories: [],
				series: []
			};
			if (list.length == 0) {
				this[key].hasData = false;
				return linedata;
			}

			linedata.categories = Object.keys(list[0].trendData);
			for (let i = 0; i < list.length; i++) {
				let item = {};
				if (unit) {
					item = {
						data: [],
						name: list[i].type,
						unit: unit
					};
				} else {
					item = {
						data: [],
						index: i,
						name: list[i].type,
						unit: this[key].tags[i].unit
					};
				}
				for (let j = 0; j < linedata.categories.length; j++) {
					item.data.push(list[i].trendData[linedata.categories[j]] * 1);
				}
				linedata.series.push(item);
			}
			// linedata.categories = this.changeDateVal(linedata.categories);
			this[key].linedata = linedata;
			console.log('linedata', linedata);
			this[key].hasData = true;
			if (this[key].lineType) {
				this.setLineChart(key);
			} else {
				this.setMoreLineChart(key);
			}
		},
		// 绘制环形图
		setLineChart(chart) {  
			let list = this[chart].linedata.series;
			let chartData = [];
			for (let i = 0; i < list.length; i++) {
				chartData.push({
					name: list[i].name,
					type: 'line',
					showSymbol:list[i].data.length <= 1 ? true : false,
					smooth: true,
					emphasis: {
						focus: 'none'
					},
					data: list[i].data
				});
			}
			this[chart].lineOpts = onelineOpt({ unit: this[chart].tags[this[chart].tagIdx].unit || '', data: chartData, categories: this[chart].linedata.categories });
			this.$nextTick(() => {
				this.$refs[chart].init(echarts, chartF => {
					// this.chartMaps[chart] = chartF 
					chartF.setOption(this[chart].lineOpts);
				});
			});
		},

		// 绘制多y轴折现图
		// 绘制环形图
		setMoreLineChart(chart) {  
			let list = this[chart].linedata.series;
			let chartData = [];
			for (let i = 0; i < list.length; i++) {
				chartData.push({
					name: list[i].name,
					type: 'line',
					// stack: 'Total',
					// areaStyle: {},
					showSymbol:list[i].data.length <= 1 ? true : false,
					smooth: true,
					yAxisIndex: i,
					// emphasis: {
					// 	focus: 'series'
					// },
					data: list[i].data
				});
			}
			this[chart].lineOpts = moreLineOpt({ data: chartData, categories: this[chart].linedata.categories });
			this.$nextTick(() => {
				this.$refs[chart].init(echarts, chartF => {
					// this.chartMaps[chart] = chartF 
					chartF.setOption(this[chart].lineOpts);
				});
			});
		},
	}
};
</script>

<style lang="scss" scoped>
@import './card.scss';
</style>
